﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;
using ESN.Models;
using System.Web.Security;
using System.Threading.Tasks;

namespace ESN.Hubs
{
    public class Presentation : Hub
    {
        private ESNCoreDbContext core = new ESNCoreDbContext();
        public void Send(CanvasData message)
        {
            if (message.type == 2)
            {
                message.data = "<b><a href='/" + Membership.GetUser().UserName + "/Home'>" + Membership.GetUser().UserName + "</a></b> : " + message.data;
            }
            Clients[Caller.GroupId].addMessage(message);
        }

        public void Join(string groupId)
        {
            Caller.GroupId = groupId;
            AddToGroup(groupId);
            CanvasData message = new CanvasData();
            message.type = 3;
            message.data = "<b><a href='/" + Membership.GetUser().UserName  + "/Home'>" + Membership.GetUser().UserName + "</a></b> just join the Presentation.";
            Clients[groupId].addMessage(message);
        }
        public void Leave()
        {
            CanvasData message = new CanvasData();
            message.type = 3;
            var session = core.CanvasSessions.Find(new Guid(Caller.GroupId));
            if (session != null)
            {
                if (session.UserId == (Guid)Membership.GetUser().ProviderUserKey)
                {
                    core.CanvasSessions.Remove(session);
                    core.SaveChanges();
                    message.data = "<b><a href='/" + Membership.GetUser().UserName + "/Home'>" + Membership.GetUser().UserName + "</a></b> - the owner - just leave the Presentation.";
                    Clients[Caller.GroupId].addMessage(message);
                    return;
                }
            }
            message.data = "<b><a href='/" + Membership.GetUser().UserName + "/Home'>" + Membership.GetUser().UserName + "</a></b> just leave the Presentation.";
            Clients[Caller.GroupId].addMessage(message);
        }
        //public Task Disconnect()
        //{
        //    return Clients.disconnected("<b><a href='/" + Membership.GetUser().UserName + "/Home'>" + Caller.Name + "</a></b> just leave the Presentation.");
        //}
    }
}